package com.fy.market.strategy.service.rule.tree.impl;

import com.fy.market.strategy.model.entity.DecrAwardStockResultEntity;
import com.fy.market.strategy.model.entity.OrderMessageEntity;
import com.fy.market.strategy.model.entity.RuleMatterEntity;
import com.fy.market.strategy.model.enums.RuleLogicCheckTypeEnum;
import com.fy.market.strategy.model.entity.tree.RuleTreeResultEntity;
import com.fy.market.strategy.repository.IStrategyRepository;
import com.fy.market.strategy.service.rule.tree.ILogicTreeNode;
import com.fy.market.types.common.ex.ExHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author fwq
 * @desc 库存操作节点
 * @date 2025年09月25
 */
@Slf4j
@Component("rule_stock")
public class RuleStockLogicTreeNode implements ILogicTreeNode {

    @Resource
    private IStrategyRepository iStrategyRepository;


    /**
     * 库存操作节点逻辑处理
     * @param ruleMatterEntity 规则节点实体
     * @return 规则树结果实体
     */
    @Override
    public RuleTreeResultEntity logic(RuleMatterEntity ruleMatterEntity) {
        Integer strategyId = ruleMatterEntity.getStrategyId();
        Integer awardId = ruleMatterEntity.getAwardId();
        Integer userId = ruleMatterEntity.getUserId();
        Integer guaranteedAwardId = ruleMatterEntity.getGuaranteedAwardId();

        // 确定最终的奖品ID
        Integer finalAwardId = guaranteedAwardId != null ? guaranteedAwardId : awardId;

        // 扣减库存
        DecrAwardStockResultEntity decrAwardStockResultEntity = iStrategyRepository.decrAwardStock(strategyId, finalAwardId);
        if (!decrAwardStockResultEntity.getCODE().equals(0)) log.error("扣减奖品库存失败，策略ID: {}, 奖品ID: {}, 错误码: {}", strategyId, finalAwardId, decrAwardStockResultEntity.getCODE());

        log.info("库存操作成功，策略ID:{} 奖品ID:{} 剩余库存:{}", strategyId, finalAwardId, decrAwardStockResultEntity.getREMAINING_STOCK());
        iStrategyRepository.sendOrder(OrderMessageEntity.builder().strategyId(strategyId).awardId(finalAwardId).userId(userId).build());
        return RuleTreeResultEntity.builder()
                .awardId(finalAwardId)
                .ruleLogicCheckTypeEnum(RuleLogicCheckTypeEnum.ALLOW)
                .build();
    }
}